package logic

import (
	"box-serve/boxserverpc/boxserverpc"
	"box-serve/boxserverpc/internal/svc"
	"box-serve/models"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ShopAddLogic) ShopAdd(in *boxserverpc.ShopAddRequest) (*boxserverpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	var class models.Class

	if err := class.FindClassByTitle(models.DB, in.ClassTitle); err != nil {
		class = models.Class{
			Title: in.ClassTitle,
		}

		if err := class.ClassAdd(models.DB); err != nil {
			return nil, err
		}
	}

	shop := models.Shop{
		Title:   in.Title,
		Price:   float64(in.Price),
		Image:   in.Image,
		Info:    in.Info,
		ClassId: int(class.ID),
	}

	if err := shop.FindShopByTitle(models.DB, in.Title); err == nil {
		return nil, fmt.Errorf("商品已存在,添加失败")
	}

	if err := shop.ShopAdd(models.DB); err != nil {
		return nil, err
	}

	return &boxserverpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
